import {
  AsyncStorage,
} from 'react-native';
import GitHubTrending from 'GitHubTrending';
// 标识
export let FLAG_STORAGE = { flag_popular: 'popular', flag_trending: 'trending' };

export default class DataRepository {
  constructor(flag) {
    this.flag = flag;
    if (flag === FLAG_STORAGE.flag_trending) this.trending = new GitHubTrending();
  }
  fetchRepository(url) {
    return new Promise((resolve, reject) => {
      // 获取本地的数据
      this.fetchLocalRepository(url)
        .then(result => {
          if (result) {
            resolve(result);
          } else {
            // 如果没有本地数据,则获取网络的数据
            this.fetchNetRepository(url)
              .then(result => {
                resolve(result);
              })
              .catch(e => {
                reject(e);
              })
          }
        })
        .catch(e => {
          // 获取网络数据出错,则获取本地数据
          this.fetchNetRepository(url)
            .then(result => {
              resolve(result);
            })
            .catch(e => {
              reject(e);
            })
        })
    })
  }
  /**
   * 获取本地数据
   * @param  url 
   */
  fetchLocalRepository(url) {
    console.log('获取本地数据');
    return new Promise((resolve, reject) => {
      // 获取本地的数据
      AsyncStorage.getItem(url, (error, result) => {
        if (!error) {
          try {
            resolve(JSON.parse(result));
          } catch (e) {
            reject(e);
          }
        } else {
          reject(error);
        }
      })
    })
  }

  /**
   *  网络请求
   * @param {string} url 
   */
  fetchNetRepository(url) {
    return new Promise((resolve, reject) => {
      // 根据flag来判断访问时最热还是趋势模块
      if (this.flag === FLAG_STORAGE.flag_trending) {
        this.trending.fetchTrending(url)
          .then(result => {
            if (!result) {
              reject(new Error('responseData is null'));
              return;
            }
            // 缓存数据
            this.saveRepository(url, result);
          })
      } else {
        fetch(url)
          .then(response => response.json())
          .then(result => {
            if (!result) {
              reject(new Error('responseData is null'))
              return;
            }
            resolve(result.items);
            // 缓存数据
            this.saveRepository(url, result.items);
          })
          .catch(error => {
            reject(error);
          })
      }
    })
  }

  /**
   * 保存数据
   * @param  url 
   * @param  items 
   * @param  callBack 
   */
  saveRepository(url, items, callBack) {
    if (!url || !items) return;
    let wrapData = { items: items, update_data: new Date().getTime() };
    AsyncStorage.setItem(url, JSON.stringify(wrapData), callBack)
  }

  /**
   * 检查数据是否过时
   * @param  longTime 数据的时间戳
   */
  checkData(longTime) {
    let cDate = new Date();
    let tDate = new Date();
    tDate.setTime(longTime);
    // 月份不同
    if (cDate.getMonth() !== tDate.getMonth()) return false;
    // 日期不同
    if (cDate.getDay() !== tDate.getDay()) return false;
    // 超过四个小时
    if (cDate.getHours() - tDate.getHours() > 4) return false;
    return true;

  }
}